(function( $, undefined ) {
/*
	\name ru Guideline-based editor
	\description ru 
	\save true
*/
$.widget("ui.ajajform_gdbeditor",$.ui.ajajform_widget, {
	options: {
		// \type cssclass
		cssclass: "afw-gdbeditor",
		// \type text
		label: "",
		// \type text
		value: [],
		styles: [],
		style: 0,
		// \type html
		htmltemplate: '<div class="af-label"></div><div class="af-value"><div class="gdbeditor-div"></div><div class="af-error"></div></div><div style="clear: both;"></div>',
//		htmltemplate_stylechooser:"<div class='af-style'><div class='af-label2'>Стиль документа <span>(можно изменить только при пустом документе)</span>:</div><div class='af-select'><select></select></div><div style='clear:both;'></div></div>",
		htmltemplate_stylechooser:"<div class='af-style'><div class='af-label2'>Стиль документа :</div><div class='af-select'><select></select></div><div style='clear:both;'></div></div>",
		htmltemplate_blocks:"<div class='af-blocks'></div>",
		htmltemplate_blockadder:"<div class='af-blocks-add'><div class='af-label2'>Добавить: </div><div class='af-bg'></div><div style='clear:both;'></div></div>",
		htmltemplate_block:"<div class='af-block'><div class='af-buttons'><div class='af-sortable'></div><div class='af-delete'></div></div><div class='af-block-main'><div class='af-block-name'></div><div class='af-content'></div></div><div style='clear:both;'></div></div>",
		// \type integer
		width: 400,
		// \type integer
		height: 200,
		// \type boolean
		readonly: false,
//		next_pos:0,
		htmltemplate_dialog: '<div><iframe src="" width="100%" height="95%" frameborder="0" border="0"></iframe></div>'
	},
	_create: function() {
		this.init();
		this.genericCreate();
		this.div=$(".gdbeditor-div",this.element);
		this.refreshWidth();
		this.create();
		this.refreshLabel();
		this.refreshStyles();
		this.refreshStyleBlocks();
		this.refreshValue();
		this.refreshReadonly();
	},

	init: function() {
	},

	create: function() {
		var t=this;
		this.div.addClass("tabs-widget-content");
		var tabh=$('<div class="tabs"><div class="cl"></div></div>').appendTo(this.div);
		var tabb=$('<div class="bodies"></div>').appendTo(this.div);
		this.tw=new TabWidget(tabh,tabb);
		var html1=this.options.htmltemplate_stylechooser+this.options.htmltemplate_blocks+this.options.htmltemplate_blockadder;
		var html2="";
		this.tw.add("gdbe-tab-edit","Редактирование",html1);
		this.tw.add("gdbe-tab-view","Просмотр",html2,function(id,bodydiv) { t.store(); t.updateView(bodydiv); });
		this.tw.select("gdbe-tab-edit");
		$(".af-style select",this.div).bind("change",function() { t.styleChanged(this); });
	},

	styleChange: function(v) {
		this.options.value=[];
		this.options.style=v;
		this.refreshStyleBlocks();
		this.refreshValue();
	},

	styleChanged: function(sel) {
		var t=this;
		if (this.options.value.length==0) {
			this.styleChange(sel.selectedIndex);
			return false;
		}
		$("<div></div>").appendTo($("body")).attr("title","Смена стиля статьи").html("<p>При смене стиля содержимое текущей статьи будет удалено. Это действие необратимо.</p>").dialog({
			resizable: false,
			height:180,
			width: 500,
			modal: true,
			buttons: [
				{text: "Сменить стиль и удалить содержимое", click: function() { t.styleChange(sel.selectedIndex);$(this).dialog("close"); }},
				{text: "Отменить", click: function() { $(this).dialog("close"); } }
			]
		});
	},

	refreshWidth: function() {
		this.div.width(this.options.width);
	},

	refreshStyles: function() {
		var sel=$(".af-style select",this.div);
		sel.options=[];
		for (var i=0;i<this.options.styles.length;i++) {
			$("<option></option>").appendTo(sel).prop("value",i).text(this.options.styles[i].name);
		}
	},

	refreshStyleBlocks: function() {
		var t=this;
		var btns=$(".af-blocks-add .af-bg",this.div);
		btns.empty();
		var st=this.options.styles[this.options.style];
		for (var i=0;i<st.blocks.length;i++) {
			var b=st.blocks[i];
			if (typeof b.fields=="string") b.fields=b.fields.split(/,\s*/);
			$('<img src=""/>').addClass('icon').attr("src",b.icon_id_url).appendTo(btns).bind("click",{i:i}, function(e) { t.addBlock(e.data.i); });
		}
		btns.append('<div style="clear: both;"></div>');
	},

	process: function(html,href) {
		html=html.replace(/\{\{(?:(\w+)(?:\("(.*)"\))?:)?(\w+)\}\}/g,function(a,func,args,varname) {
			var t=href[varname];
			if (t==undefined) t="";
			switch(func) {
				case "T":
				case "B":
				case "Bminus":
				case "P":
				case "Pminus":
				case "I":
				case "LI":
					t=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
					break;
			}
			if (func=="Pminus" || func=="Bminus") {
				t=t.replace(/&lt;(\/?)([biua]|h\d)&gt;/ig,function(a,p1,p2) { return "<"+p1+p2+">";});
				t=t.replace(/&lt;a\s+href="(\/[^"]*|http:[^"]*)"&gt;/ig,function(a,p1) { return "<a href=\""+p1+"\">";});
			}
			switch(func) {
				case "preview":
					t=mkpreview(t,args);
					break;
				case "LI":
					t="<li>"+t.replace(/\n/g,"</li><li>")+"</li>";
					break;
				case "IMG":
					var name=varname;
					var value=t;
//					var value_name=href[p2+"_name"]||"";
					t="";
					t+="<div class='af-image-selector'>";
					t+="<input type='hidden' class='"+name+"' value='"+value+"'/>";
					t+="<div class='af-line'><img src='"+(args?mkpreview(value,args):value)+"' class='preview imgpreview-"+name+"' alt='"+args+"'></div>";
					t+="<div class='af-line'><input type='button' class='image-select-button imgselname-"+name+"' value='Выбрать из загруженных'/></div>";
//					t+="<div class='af-line'><input type='file'><input type='button' value='Загрузить'/></div>";
					t+="</div>";
					break;
				case "I":
					t=t.replace(/\n/g,"\\n").replace(/'/g,"\\'").replace(/"/g,"\\\"");
					break;
				case "B":
				case "Bminus":
					t=t.replace(/\n/g,"<br/>\n");
					break;
				case "P":
				case "Pminus":
					t=t.replace(/\n/g,"</p>\n<p>\n");
					break;
			}
//			console.log({func:func,args:args,varname:varname,t:t});
			return t;
		});
		return html;
	},

	addBlock: function(n) {
		this.store();
		var max_pos=0;
		for (var i=0;i<this.options.value.length;i++) {
			if (this.options.value[i].pos>max_pos) max_pos=this.options.value[i].pos; 
		}
		var b=this.options.styles[this.options.style].blocks[n];
		var value={type:n,pos:max_pos+1};
		for (var i=0;i<b.fields.length;i++) value[b.fields[i]]="";
		this.options.value.push(value);
//		this.options.next_pos++;
		
		this.addBlockRender(value);
//		this.refreshValue();
	},

	sortedBlocks: function(e,ui,blocks) {
		var t=this;
		var tmp={};
		for (var i=0;i<this.options.value.length;i++) tmp[this.options.value[i].pos]=this.options.value[i];
		this.options.value=[];
		$(".af-blocks .af-block").each(function(i,tag) {
			var a=tag.className.match(/pos-(\d+)/);
			t.options.value.push(tmp[a[1]]);
		});
//		console.log(this.options.value);
//		$(this).sortable('toArray')
	},

	deleteBlock: function(pos) {
		var i=0;
		while (this.options.value[i].pos!=pos) {
			if (i>=this.options.value.length) return;
			i++;
		}
		$(".af-blocks .af-block",this.div).eq(i).remove();
		this.options.value.splice(i,1);
	},

	store: function() {
		var t=this;
		var tmp={};
		for (var i=0;i<this.options.value.length;i++) tmp[this.options.value[i].pos]=this.options.value[i];
		$(".af-blocks .af-block").each(function(i,tag) {
			var a=tag.className.match(/pos-(\d+)/);
			t.storeBlock(tmp[a[1]],tag);
		});
	},

	storeBlock: function(value,tag) {
//		console.log(value);
		var b=this.options.styles[this.options.style].blocks[value.type];
		for (var i=0;i<b.fields.length;i++) {
			var t=$("."+b.fields[i],tag).val();
			if (t==undefined) {
				t="";
				console.log({pos:value.pos,field:b.fields[i],error:"empty data"});
			}
			value[b.fields[i]]=t;
		}
	},

	updateView: function(bodydiv) {
		bodydiv.empty();
		if (typeof this.options.value == "string") return;
		for (var i=0;i<this.options.value.length;i++) {
			var value=this.options.value[i];
			var b=this.options.styles[this.options.style].blocks[value.type];
			$(this.process(b.preview_html,value)).appendTo(bodydiv);
		}
	},
	
	getBlock: function(pos) {
		var i=0;
		var v=this.options.value;
		while (i<v.length) {
			if (v[i].pos==pos) return v[i];
			i++;
		}
		return undefined;
	},

	imageSelectClicked: function(pos,field) {
		var b=this.getBlock(pos);
		this.openFileChooseDialog(pos,field,b[field]);
//		this.imageSelectDone(pos,field,"/f/images/23/36-preview3.jpg");
	},
	
	openFileChooseDialog: function(pos,field,filename) {
		var d=global_ajajform_file_id_dialog=$(this.options.htmltemplate_dialog).appendTo($("body"));
		var tail="";
		if (this.options.defaultFileGroupId) {
			tail="&file_group_id="+this.options.defaultFileGroupId;
		} else if (filename && filename.match(/^\/f\//)) {
			tail="&file_id="+filename.match(/\/(\d+)(?:-preview\w+|)\./)[1];
		}
		$("iframe",d).attr("src","/admin_popup-filebrowser/?target=ajajform_gdbe"+tail);
		global_ajajform_file_id={pos:pos,field:field,t:this};
		var wx=Math.floor(win_x()*0.90)-100;
		var wy=Math.floor(win_y()*0.90)-100;
		d.dialog({
			modal: true,
			width: wx<830?830:wx,
			height: wy<550?470:wy,
			close: function() { d.dialog("destroy");d.remove(); }
		});
	},

	imageSelectDone: function(pos,field,url) {
		$(".af-blocks .af-block.pos-"+pos+" ."+field).val(url);
		var size=$(".af-blocks .af-block.pos-"+pos+" .imgpreview-"+field).attr("alt");
		$(".af-blocks .af-block.pos-"+pos+" .imgpreview-"+field).attr("src",mkpreview(url,size||"2C"));
		var b=this.getBlock(pos);
		b[field]=url;
	},	

	addBlockRender: function(value) {
		var t=this;
		var b=this.options.styles[this.options.style].blocks[value.type];
		var blocks=$(".af-blocks",this.div);
		var div=$(this.options.htmltemplate_block).appendTo(blocks);
		$(".af-block-name",div).text(b.name);
		$(".af-content",div).html(this.process(b.edit_html,value));
		$(".af-delete",div).bind("click",function() { t.deleteBlock(value.pos); });
		div.addClass("pos-"+value.pos);
		$(".af-blocks").sortable({
			handle: ".af-sortable",
			stop: function(event,ui) { t.sortedBlocks(event,ui,this); }
		});
		var pos=value.pos;
		$(".image-select-button",div).button().bind("click",function() { t.imageSelectClicked(pos,this.className.match(/imgselname-(\w+)/)[1] ); });
	},

	restoreValue: function() {
		if (this.options.value=="") {
			this.options.value=[];
			return;
		}
		console.log(this.options.value);
		var tmp=JSON.parse(this.options.value);
		for (var i=0;i<this.options.styles.length;i++) if (this.options.styles[i].id==tmp.style_id) this.options.style=i;
		var h={};
		var st=this.options.styles[this.options.style];
		for (var i=0;i<st.blocks.length;i++) h[st.blocks[i].id]=i;
		this.refreshStyleBlocks();
		this.options.value=tmp.value;
		for (var i=0;i<this.options.value.length;i++) {
			this.options.value[i].type=h[this.options.value[i].block_id];
			this.options.value[i].pos=i+1;
		}
	},

	refreshValue: function() {
		if (typeof this.options.value == "string") this.restoreValue();
		var t=this;
		var blocks=$(".af-blocks",this.div).empty();
		for (var i=0;i<this.options.value.length;i++) {
			this.addBlockRender(this.options.value[i]);
		}
	},

	refreshReadonly: function() {
//		$("textarea",this.element).prop("readonly",this.options.readonly);
	},

	destroy: function() {
	},

	validate: function() {
		this.store();
		return false;
	},

	postvalue: function(r) {
		this.store();
		var st=this.options.styles[this.options.style];
		for (var i=0;i<this.options.value.length;i++) {
			v=this.options.value[i];
			v.block_id=st.blocks[v.type].id;
		}
		r[this.options.name]=JSON.stringify({style_id:st.id,value:this.options.value});
	}
});

})( jQuery );

function ajajform_gdbe_set(url)
{
	global_ajajform_file_id.t.imageSelectDone(global_ajajform_file_id.pos,global_ajajform_file_id.field,url);
	global_ajajform_file_id=undefined;
	global_ajajform_file_id_dialog.dialog("close");
}

